
const { ccclass, property, menu, executionOrder } = cc._decorator;
/** 分帧加载辅助工具
 * API : startLoading
 *       stopLoading
 * 
 * 
 * 
 */
@ccclass
@executionOrder(-1) //总是先执行
@menu("自定义组件/分帧加载")
export default class FramesLoadingHelper extends cc.Component {

    _isStop = true;
    _data: {
        oneDo: number,
        totalDo: number,
        step: number,
        callBack: (index: any) => any
    }


    _CumulativeDt: number

    _nowDo: number
    _startTimer: number
    onLoad() {
        this._isStop = true;
        this._CumulativeDt = 0;
    }
    
    /** 开始分帧加载
     * 
     *
     *  @param oneDo: number,                单次执行callBack次数
     *  @param totalDo: number,              总执行callBack次数
     *  @param step: number,                 每次执行间隔时间 s
     *  @param callBack: (index: any) => any 回调
     *  @param index 当前执行位置
     */
    startLoading(data: {
        oneDo: number,
        totalDo: number,
        step: number,
        callBack: (index: any) => any
    }) {
        this._nowDo = 0;
        this._CumulativeDt = 0;
        this._isStop = false;
        this._data = data
        this._startTimer = new Date().getTime()
    }

    /** 停止分帧加载
     * 
     */
    stopLoading() {
        let dur = new Date().getTime() - this._startTimer;
        cc.log(`分帧加载完毕,间隔${this._data.step * 1000}毫秒,每次加载${this._data.oneDo},已加载${this._nowDo}/${this._data.totalDo},总耗时${dur}毫秒,实际单次耗时${dur / (this._data.totalDo / this._data.oneDo)}毫秒`)
        this._isStop = true;
    }

    update(dt: any) {
        if (!this._isStop) {
            this._CumulativeDt += dt;
            if (this._CumulativeDt > this._data.step) {
                this._CumulativeDt = 0;
                for (let i = 0; i < this._data.oneDo && this._nowDo < this._data.totalDo; i++) {
                    this._data.callBack && this._data.callBack(this._nowDo)
                    // cc.log(`分帧加载中,已加载${this._nowDo + 1}/${this._data.totalDo}`)
                    this._nowDo++
                }
                this._nowDo == this._data.totalDo && this.stopLoading();
            }


        }
    }
}
